<template>
  <div class="manage-user">
    <el-card class="manage-card animated">
      <h1 class="title">用户管理</h1>
      <div class="action-bar">
        <el-input v-model="searchUsername" placeholder="搜索用户名" clearable class="search-input" />
        <el-button type="primary" @click="handleSearch" class="action-button">搜索</el-button>
      </div>

      <el-table :data="users.list" style="width: 100%" v-loading="loading" border stripe class="manage-table">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="quota" label="配额" />
        <el-table-column prop="apikey" label="API Key" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEditDialog(scope.row)" class="action-button">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)" class="action-button">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="pagination.total"
          :current-page="pagination.current"
          :page-size="pagination.pageSize"
          @current-change="handlePageChange"
        />
      </div>

      <div class="bottom-right-button">
        <el-button type="danger" @click="handleExit" class="action-button">退出</el-button>
      </div>

      <el-dialog v-model="editDialogVisible" title="编辑用户" width="400px" class="dialog">
        <el-form :model="editForm" label-width="100px" label-position="top">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" />
          </el-form-item>
          <el-form-item label="角色">
            <el-input v-model="editForm.role" />
          </el-form-item>
          <el-form-item label="配额">
            <el-input-number v-model="editForm.quota" :min="0" />
          </el-form-item>
          <el-form-item label="API Key">
            <el-input v-model="editForm.apikey" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="addDialogVisible" title="新增用户" width="400px" class="dialog">
        <el-form :model="addForm" label-width="100px" label-position="top" ref="addFormRef">
          <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
            <el-input type="password" v-model="addForm.password" show-password />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="addForm.role">
              <el-option label="普通用户" value="public" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAdd">确认添加</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const { users, loading, pagination } = storeToRefs(userStore)
const searchUsername = ref('')
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const addFormRef = ref(null)

const editForm = ref({
  id: null,
  username: '',
  role: '',
  quota: 0,
  apikey: ''
})

const addForm = ref({
  username: '',
  password: '',
  role: 'public'
})

onMounted(() => {
  userStore.fetchUsers()
})

function openEditDialog(user) {
  editForm.value = { ...user }
  editDialogVisible.value = true
}

function handleSearch() {
  userStore.fetchUsers({ page: 1, username: searchUsername.value })
}

const handleExit = async () => {
  await router.push('/admin')
}

async function submitEdit() {
  const success = await userStore.updateUser(editForm.value.id, {
    username: editForm.value.username,
    role: editForm.value.role,
    quota: editForm.value.quota,
    apikey: editForm.value.apikey
  })
  if (success) {
    ElMessage.success('更新成功')
    editDialogVisible.value = false
  } else {
    ElMessage.error(userStore.error || '更新失败')
  }
}

async function submitAdd() {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const success = await userStore.createUser({
          username: addForm.value.username,
          password: addForm.value.password,
          role: addForm.value.role
        })
        if (success) {
          ElMessage.success('用户添加成功')
          addDialogVisible.value = false
        }
      } catch (error) {
        console.error('Add user error in component:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

async function handleDelete(userId) {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个用户吗？删除后无法恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    const success = await userStore.deleteUser(userId)
    if (success) {
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(userStore.error || '删除失败')
    }
  } catch (error) {
    console.log('取消删除', error)
  }
}

function handleAdd() {
  addDialogVisible.value = true
}

function handlePageChange(page) {
  userStore.fetchUsers({ page })
}
</script>

<style scoped>
@keyframes slideUpFadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.manage-user {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.manage-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  background: #ffffff;
  animation: slideUpFadeIn 0.7s ease-out forwards;
  height: 800px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  text-align: center;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.action-button {
  border-radius: 8px;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.manage-table {
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.bottom-right-button {
  margin-top: 20px;
  text-align: right;
}

.dialog {
  border-radius: 12px;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus) {
  background-color: #fff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
}

@media (max-width: 768px) {
  .manage-user {
    padding: 10px;
  }

  .manage-card {
    padding: 15px;
  }

  .title {
    font-size: 20px;
  }

  .action-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .action-button {
    padding: 8px 16px;
    font-size: 14px;
  }
}
</style>
